<script setup lang="ts">
import { type PositionSchema } from "@/types/account.types";
import { usePositionTable } from "./Position";
import TagSelector from "@/components/tag-selector/TagSelector.vue";
import { usePositionSorting } from "@/composables/useAccountTable/usePositionSorting";

defineOptions({
  name: "position"
});

const props = withDefaults(
  defineProps<{
    positions: PositionSchema[];
    height?: string | null;
    size?: "small" | "default" | "large";
    title?: string;
    compact?: boolean;
  }>(),
  {
    height: null,
    size: undefined,
    title: undefined,
    compact: false
  }
);

const selectedPositionIdModel = defineModel<string | null>(
  "selectedPositionId"
);

const { positionColumns, tableSize, handleRowClick, tableRef } =
  usePositionTable(props.compact, selectedPositionIdModel);

const {
  POSITION_SORT_PRESETS,
  selectedPresetModel,
  sort,
  handleSortChange,
  setHeaderCellClass
} = usePositionSorting();

const presetTags = POSITION_SORT_PRESETS.map(p => p.name);
</script>

<template>
  <div
    :class="[
      'w-full',
      props.height ? 'flex h-full flex-col' : '',
      props.compact ? 'compact-mode' : ''
    ]"
  >
    <div class="mb-2 flex items-center gap-3">
      <span v-if="props.title" class="text-sm font-medium text-gray-700">{{
        props.title
      }}</span>
      <span class="text-xs text-gray-600">快速排序:</span>
      <TagSelector v-model="selectedPresetModel" :tags="presetTags" />
    </div>
    <div :class="props.height ? 'min-h-0 flex-1 overflow-hidden' : ''">
      <pure-table
        ref="tableRef"
        :size="props.size ?? tableSize"
        :data="sort(positions)"
        :columns="positionColumns"
        :row-key="row => row.vt_position_id"
        :header-cell-class-name="setHeaderCellClass"
        :height="props.height"
        :highlight-current-row="true"
        @sort-change="handleSortChange"
        @row-click="handleRowClick"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.compact-mode :deep(.el-table--small .cell) {
  padding: 0 4px;
}

@media screen and (width <= 768px) {
  :deep(.el-table--small .cell) {
    padding: 0 4px;
  }
}
</style>
